<?php

ignore_user_abort(true);
set_time_limit(0);

if (!file_exists(dirname(__FILE__) . '/cron-run')) {
    exit();
}

do {
    if (!file_exists(dirname(__FILE__) . '/cron-switch')) {
        break;
    }
    //开关作用
    sleep(1);
    $sockdata = _sock("http://127.0.0.1/fanyi_create_html.php");
    if ($sockdata['error_code'] == '0') {
        echo $sockdata['error_msg']."OK\n";
    } else {
        echo $sockdata['error_msg']."\n";
    }
} while (true);

function _sock($url)
{
    $host = parse_url($url, PHP_URL_HOST);
    $port = parse_url($url, PHP_URL_PORT);
    $port = $port ? $port : 80;
    $scheme = parse_url($url, PHP_URL_SCHEME);
    $path = parse_url($url, PHP_URL_PATH);
    $query = parse_url($url, PHP_URL_QUERY);
    if ($query) {
        $path .= '?' . $query;
    }

    if ($scheme == 'https') {
        $host = 'ssl://' . $host;
    }

    $fp = fsockopen($host, $port, $error_code, $error_msg, 1);
    if (!$fp) {
        return array('error_code' => $error_code, 'error_msg' => $error_msg);
    } else {
        stream_set_blocking($fp, true); //开启了手册上说的非阻塞模式
        stream_set_timeout($fp, 60); //设置超时
        $header = "GET $path HTTP/1.1\r\n";
        $header .= "Host: $host\r\n\r\n";
        $header .= "Connection: close\r\n\r\n"; //长连接关闭
        fputs($fp, $header);
        usleep(1000); // 这一句也是关键，如果没有这延时，可能在nginx服务器上就无法执行成功
        fclose($fp);
        return array('error_code' => 0,'error_msg'=>$header);
    }
}

